"ui";
importClass(android.graphics.Color);
importClass(android.graphics.drawable.GradientDrawable);
// 数据
var storage = storages.create("autotouchYuanshen");
const project = require('./project.json');
//参数声明
var appPackageName = "com.qqgame.mic";
var deviceWidth = device.width;
var deviceHeight = device.height;
var picJizhun = 1;
var picJizhunHeight = 1;
var version = project.versionName;   //版本号
var setYanchi = 10;

ui.layout(
    <ScrollView>
        <vertical>
            <appbar>
                <toolbar id="appTitle" title="道一科技" />
            </appbar>
            <Switch id="autoService" text="无障碍服务" checked="{{auto.service != null}}" padding="8 8 8 8" textSize="15sp" />
            <horizontal>
                <text text="  激活码：" gravity="left" />
                <input id="jihuoma" hint="请输入注册码" textSize="15sp" inputType="text" gravity="left" w="*" />
            </horizontal>
            <horizontal marginTop="10sp" padding="12sp" bg="#99FE01">
                <checkbox id="ceshji" text="运行后是否测试一次" />
                <checkbox id="rizhishuchu" text="是否开始日志输出" />
                
            </horizontal>
            <horizontal marginTop="10sp" padding="12sp" bg="#FFFF01">
                <text text=" 时：" gravity="left" textColor="#000000"/>
                <input id="myShi" hint="时" textSize="15sp" inputType="number" gravity="center" />
                <text text="  分：" gravity="left" textColor="#000000"/>
                <input id="myFen" hint="分" textSize="15sp" inputType="number" gravity="center" />
                <text text="  秒：" gravity="left" textColor="#000000"/>
                <input id="myMiao" hint="秒" textSize="15sp" inputType="number" gravity="center" />
            </horizontal>
            <horizontal marginTop="10sp" padding="12sp" bg="#99FE01">
                <text text=" 延迟速度：" gravity="left" textColor="#000000"/>
                <input id="setYanshi" textSize="15sp" inputType="number" gravity="center" />
                <text text=" 毫秒 1秒=1000毫秒 ！不建议修改！" gravity="left" textColor="#000000"/>
            </horizontal>
            <text text="   公告：" textColor="#E63F31" textSize="14sp" marginTop="8sp"/>
            <text id="gonggao" text="见面发财，黄金万两! " textColor="#E63F31" textSize="15sp" paddingLeft="10sp"/>
            <text text="   欢迎使用道一科技系列产品" gravity="left" marginTop="6sp" />
            <text autoLink="web" text="   官网：http://daoyikeji.com/yxs.html" gravity="left" />
            <text text="   淘宝：道一科技店" gravity="left"  />
            <text text="   温馨提示：" gravity="left" marginTop="6sp" />
            <text text="   1.请于周一十点前运行本软件，点击“开始运行”；" gravity="left" />
            <text text="   2.软件运行后请打开英雄杀并打开元神召唤页面；" gravity="left" />
            <text text="   3.点击悬浮框按钮“开”；" gravity="left" />
            <text text="   4.悬浮框变成绿色“运”开始执行脚本；" gravity="left" />
            <text text="   5.再次点击悬浮窗停止(执行中无法点击)；" gravity="left" />
            <text text="   6.音量上键结束运行!；" gravity="left" />
            <horizontal>
                <text text="   系统提示：" gravity="left" />
                <checkbox id="支持" text="本软件无需root权限。" checked="true" />
            </horizontal>

            <horizontal>
                <text id="appVersion" text="   当前软件版本：  " gravity="left" />
                <text id="androidVer" textSize="15sp" />
            </horizontal>
            <horizontal marginTop="6sp">
                <button id="start" text="开始运行" layout_weight="1" style="Widget.AppCompat.Button.Colored" />
            </horizontal>

        </vertical>
    </ScrollView>
);

ui.androidVer.text("   本机安卓版本：" + device.release + "");
ui.appVersion.text("   当前软件版本：" + version + "     ");
ui.appTitle.title = "道一科技 - 元神召唤 v " + version;
ui.autoService.on("check", function (checked) {
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    }
});
readconfig()

//记录按键被按下时的触摸坐标
var x = 0, y = 0;
//记录按键被按下时的悬浮窗位置
var windowX, windowY;
// 悬浮窗
var floatyWindow;
// 运行
var yunxingIng = false;

function xuanfuFunc() {
    floatyWindow = floaty.window(
        <horizontal >
            <button id="floatyAction" text="开" textSize="12sp" w="35" h="35"></button>
            <button id="myExit" text="退出" textSize="12sp" w="40" h="35" bg="#02FE99" marginLeft="8sp" />
        </horizontal >
    );

    floatyWindow.floatyAction.setOnTouchListener(function (view, event) {
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                x = event.getRawX();
                y = event.getRawY();
                windowX = floatyWindow.getX();
                windowY = floatyWindow.getY();
                return true;
            case event.ACTION_MOVE:
                //移动手指时调整悬浮窗位置
                floatyWindow.setPosition(windowX + (event.getRawX() - x), windowY + (event.getRawY() - y));
                return true;
            case event.ACTION_UP:
                //手指弹起时如果偏移很小则判断为点击
                if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
                    // log('点击悬浮窗')
                    floatyActionOnClick();
                }
                return true;
        }
        return true;
    });

    floatyWindow.myExit.on("click", function () {
        ui.finish()
    })

    floatyWindow.myExit.setVisibility(8);
    setBackgroundRoundRounded(floatyWindow.floatyAction, Color.YELLOW);
}

function setBackgroundRoundRounded(view, bloo) {
    gradientDrawable = new GradientDrawable();
    gradientDrawable.setShape(GradientDrawable.RECTANGLE);
    gradientDrawable.setColor(bloo);
    gradientDrawable.setCornerRadius(80);
    view.setBackground(gradientDrawable);
}


function floatyActionOnClick() {
    if (floatyWindow.floatyAction.getText() == '运') {
        // execution = engines.execScriptFile(path);
        yunxingIng = false;
        // console.hide()
        threads.shutDownAll()
        setBackgroundRoundRounded(floatyWindow.floatyAction, Color.RED);
        floatyWindow.myExit.setVisibility(0);
        floatyWindow.floatyAction.setText('停');
    } else if (floatyWindow.floatyAction.getText() == '停') {
        // if(execution){
        //     execution.getEngine().forceStop();
        // }
        cishu = 0;
        yunxingIng = true;
        qiangaFunc()
        floatyWindow.myExit.setVisibility(8);
        setBackgroundRoundRounded(floatyWindow.floatyAction, Color.GREEN);
        floatyWindow.floatyAction.setText('运');
        log("再次执行...")
    } else {
        cishu = 0;
        yunxingIng = true;
        floatyWindow.myExit.setVisibility(8);
        setBackgroundRoundRounded(floatyWindow.floatyAction, Color.GREEN);
        floatyWindow.floatyAction.setText('运');
        log("执行任务...")
        mainFunc();
        
    }
}


function saveconfig() {
    storage.put("jihuoma", ui.jihuoma.text());
    storage.put("setYanshi", ui.setYanshi.text());
    storage.put("ceshji", ui.ceshji.checked); 
    storage.put("rizhishuchu", ui.rizhishuchu.checked);
    storage.put("myShi", ui.myShi.text());
    storage.put("myFen", ui.myFen.text());
    storage.put("myMiao", ui.myMiao.text());
    log('保存配置')
}

function readconfig() {
    ui.jihuoma.text(storage.get("jihuoma", ""));
    ui.setYanshi.text(storage.get("setYanshi", "10"));
    ui.ceshji.checked = Boolean(storage.get("ceshji", false));
    ui.rizhishuchu.checked = Boolean(storage.get("rizhishuchu", true));
    ui.myShi.text(storage.get("myShi", "9"));
    ui.myFen.text(storage.get("myFen", "59"));
    ui.myMiao.text(storage.get("myMiao", "59"));
}

function getDaysBetween(date1, date2) {
    var startDate = Date.parse(date1);
    var endDate = Date.parse(date2);
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    return days;
}

var shunxu = ['纣王', '鳌拜', '祝融夫人', '高俅', '吴三桂']


// var HeroDataFrom2023 = {
//     'zhouwang': ['11-27', '01-01', '02-05'],
//     'aobai': ['12-04', '01-08', '02-12'],
//     'zhurong': ['12-11', '01-15', '02-19'],
//     'gaoqiu': ['12-18', '01-22', '02-26'],
//     'wusangui': ['12-25', '01-29',],
// }

ui.start.on("click", function () {
    log('屏幕分辨率', deviceWidth, deviceHeight)
    // 保存配置
    saveconfig()
    //程序开始运行之前判断无障碍服务
    if (auto.service == null) {
        toastLog("请先开启无障碍服务！");
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
        return;
    } else {
        log('已获取无障碍权限');
    }
    // 悬浮窗按钮
    if (!floaty.checkPermission()) {
        // 没有悬浮窗权限，提示用户并跳转请求
        toastLog("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
        floaty.requestPermission();
        return;
    } else {
        log('已获取悬浮窗权限');
    }
    
    // 控制台
    consoleThreads = threads.start(function () {
        if (Boolean(storage.get("rizhishuchu", true))) {
            console.setTitle("道一科技");
            console.show(true);
            console.setSize(400, 200);
            console.setPosition(140, 20);
        }
        log(1)
        //获取截图权限 安卓版本高于Android 9
        if(device.sdkInt>27){
            log(2.5)
            //等待截屏权限申请并同意
            threads.start(function () {
                log(2.6)
                if (device.brand == "HUAWEI") {
                    packageName('com.android.systemui').text('允许').waitFor();
                    sleep(500)
                    text('允许').click();
                } else {
                    packageName('com.android.systemui').text('立即开始').waitFor();
                    sleep(500)
                    text('立即开始').click();
                }
            });
        }
        log(3)
        log(4)
        //申请截屏权限
        if (!requestScreenCapture(true)) {
            toastLog("请求截图失败");
        }
        log(5)
        //启用按键监听
        events.observeKey();
        //监听音量上键按下
        events.onKeyDown("volume_up", function(event){
            log("停止脚本");
            yunxingIng = false;
            exit()
        });
    })
    log('打开悬浮窗')
    // 打开悬浮窗
    xuanfuFunc()
    var systemTime = new Date()
    log("执行：",getData(systemTime))
    // 基础提示
    let data = getDaysBetween('2023-11-27', getYmd(new Date()))
    data = data / 7
    if (!(/(^[1-9]\d*$)/.test(data))) {
        toastLog('今天不是周一!', data)
        // ui.finish()
    }else{
        data = Math.trunc(data)
        data = data % 5
        log('今日召唤：', shunxu[data])
    }
    log("请调整至游戏元神召唤页面后")
    toastLog("打开召唤页面后点击左上角“开”")

    // mainFunc();
});


// 数据方法
function getData(n) {
    let now = new Date(n),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
    return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}

function getYmd(n) {
    let now = new Date(n),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
    return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
}

function getMonthAndDay(n) {
    let now = new Date(n),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
    return (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
}


// 函数时间
var cishu = 0;
var shi = 9;
var fen = 59;
var miao = 59;
// 执行事件
function qiangaFunc() {
    againThreads = threads.start(function () {
        shi = Number(storage.get("myShi", "9"))
        fen = Number(storage.get("myFen", "59"))
        miao = Number(storage.get("myMiao", "59"))
        log('预约时间', shi, fen, miao)
        sleep(500)
        let storageP = storage.get("zhaohuana", {});
        log('执行坐标', storageP)
        sleep(1000)
        let datas1 = new Date()
        // 目标时间
        let datas2 = new Date( datas1.getFullYear(),datas1.getMonth(),datas1.getDate(), shi, fen, miao ).getTime()
        // 现在时间
        let datas3 = new Date().getTime()
        let chas = datas2-datas3;
        log( '倒计时s', parseInt(chas/1000) )

        let setIntervals1 = setInterval(() => {
            let datas1 = new Date()
            // 目标时间
            let datas2 = new Date( datas1.getFullYear(),datas1.getMonth(),datas1.getDate(), shi, fen, miao ).getTime()
            // 现在时间
            let datas3 = new Date().getTime()
            let chas = datas2-datas3;
            log( '倒计时', parseInt(chas/1000), '秒' )
            if (parseInt(chas/1000) < 6) {
                log( '即将开始！')
                clearInterval(setIntervals1)
            }
        },1000)
        setYanchi = storage.get("setYanshi", "10")
        if (setYanchi < 5) {
            setYanchi = 5
        }
        let setTimeouts = setTimeout(() => {
            clearTimeout(setTimeouts)
            let date = new Date().getTime();
            log('开始时间',date)
            log('执行中...')
            while (yunxingIng) {
                cishu++;
                press(storageP.x+28, storageP.y+20, 1);
                sleep(setYanchi)
                press(storageP.x+88, storageP.y+10, 1);
            }
            let date1 = new Date().getTime();
            log('结束时间',date1)
            log('完成')
            let s = Math.trunc((date1-date)/1000);
            log('召唤'+cishu+'次，用时',s)
        }, chas);
        


    })
}


// 按钮查找
function kaishizhaoFunc(){
    // 判断程序
    // log(currentPackage())
    // log(currentActivity())

    let storagePp = storage.get("zhaohuana", {});
    if (storagePp.x) {
        log("已存在坐标无需重新获取")
        if (Boolean(storage.get("ceshji", false))) {
            log('测试点击')
            click(storagePp.x+28, storagePp.y+20)
            sleep(1000)
            click(storagePp.x+88, storagePp.y+20)
        }
        return true;
    }
    // 寻找按钮
    let cap = captureScreen();
    log("基准", picJizhun)
    let thisImgs = images.read("./res/kaishizhaohuan.png");
    toastLog("opencv scale")
    thisImgs = images.scale(thisImgs, picJizhun, picJizhunHeight);
    toastLog("opencv findImage")
    let p = findImage(cap, thisImgs, { region: [0, (deviceHeight / 2), deviceWidth, (deviceHeight / 2)], threshold: 0.8 });
    // let result = images.matchTemplate(captureScreen(), thisImgs, { region: [0, (deviceHeight / 2), deviceWidth, (deviceHeight / 2)], threshold: 0.55, max: 2 });
    // log(result)
    // return
    toastLog("捕获成功")
    thisImgs.recycle();
    if (p) {
        storage.put("zhaohuana", p);
        sleep(1000)
        let storageP = storage.get("zhaohuana", {});
        log('坐标', storageP)
        if (Boolean(storage.get("ceshji", false))) {
            log('测试点击')
            click(p.x+28, p.y+20)
            sleep(1000)
            click(p.x+88, p.y+20)
        }
        return true;
    } else {
        log('当前不是英雄杀召唤页面，请调整后重新运行！')
        // captureScreen("/sdcard/screencapture1.png");
        let thisImgs1 = images.read("./res/kaishizhaohuan.png");
        thisImgs1 = images.scale(thisImgs1, picJizhun, picJizhunHeight)
        let result = images.matchTemplate(captureScreen(), thisImgs1, {region: [0, (deviceHeight/2), deviceWidth, (deviceHeight/2)],threshold: 0.7, max: 1});
        thisImgs1.recycle();
        if (result.length) {
            log('尝试结果',result)
            exit()
        } else {
            log('没有找到匹配图片')
            exit()
        }
        return false;
    }
}

// 请求服务器
function autoServerFunc() {
    let androidId = device.getAndroidId();
    var req = http.postJson("http://123.60.43.199:8866/main/v1/auto/yxsYxzhApp", {
        activationCode: storage.get("jihuoma", ""),
        aap: "yxsYxzh",
        deviceWidth: deviceWidth,
        deviceHeight: deviceHeight,
        brand: device.brand,
        versionCode: project.versionCode,
        release: device.release,
        sdkInt: device.sdkInt,
        androidId: androidId,
        fingerprint: device.fingerprint,
        // mac: device.getMacAddress(),
        // iMEI: device.getIMEI(),
        startTime: new Date().getTime()
    });
    var rJson = req.body.json();
    if (rJson.code != 200) {
        let message = rJson.message ? rJson.message : "服务异常请联系客服！";
        toastLog(message)
        sleep(2000)
        exit()
        sleep(1000)
        ui.finish()
    } else {
        ui.gonggao.text(String(rJson.data))
        log("服务成功注册！")
    }
}

// 主进程
function mainFunc() {
    // auto.waitFor()
    // //获取截图权限 安卓版本高于Android 9
    // if(device.sdkInt>27){
    //     log(2.5)
    //     //等待截屏权限申请并同意
    //     threads.start(function () {
    //         log(2.6)
    //         if (device.brand == "HUAWEI") {
    //             packageName('com.android.systemui').text('允许').waitFor();
    //             text('允许').click();
    //         } else {
    //             packageName('com.android.systemui').text('立即开始').waitFor();
    //             text('立即开始').click();
    //         }
    //     });
    // }
    // if (!requestScreenCapture(true)) {
    //     toastLog("请求截图失败");
    // }
    主线程 = threads.start(function () {
        // log(1)
        // auto.waitFor()
        log("新线程")
        // threads.start(function () {
            // if (Boolean(storage.get("rizhishuchu", true))) {
            //     console.setTitle("道一科技");
            //     console.show(true);
            //     console.setSize(400, 300);
            //     console.setPosition(140, 20);
            // }
            //启用按键监听
            // events.observeKey();
            // //监听音量上键按下
            // events.onKeyDown("volume_up", function(event){
            //     log("停止脚本");
            //     yunxingIng = false;
            //     exit()
            // });
        // });
        //获取截图权限 安卓版本高于Android 9
        // if(device.sdkInt>27){
        //     log(2.5)
        //     //等待截屏权限申请并同意
        //     threads.start(function () {
        //         log(2.6)
        //         if (device.brand == "HUAWEI") {
        //             packageName('com.android.systemui').text('允许').waitFor();
        //             text('允许').click();
        //         } else {
        //             packageName('com.android.systemui').text('立即开始').waitFor();
        //             text('立即开始').click();
        //         }
        //     });
        // }
        autoServerFunc();
        // log(3)
        // sleep(3000)
        // log(4)
        // //申请截屏权限
        // if (!requestScreenCapture(true)) {
        //     toastLog("请求截图失败");
        // }
        // log(5)
        sleep(2000)
        deviceWidth = device.width > device.height ? device.width : device.height ;
        deviceHeight = device.height > device.width ? device.width : device.height ;
        log('分辨率', deviceWidth, deviceHeight)
        picJizhun = deviceHeight / 1080;
        picJizhunHeight = deviceHeight / 1080;
        log('分辨率基准：', picJizhun)
        sleep(1000)
        // 寻找按钮
        kaishizhaoFunc();
        // 执行
        qiangaFunc();
    })
}





// var startClickTime = 1699235999000;
// // startClickTime = '1699206910000';
// var currentTime = new Date().getTime();
// var timeDifference = startClickTime - currentTime;
// log(timeDifference)
// if (timeDifference > 60000) {
//     let fenzhong =  Math.trunc(timeDifference/60/1000);
//     let miaozhong = Math.trunc((timeDifference - (fenzhong*60*1000)) /1000)
//     toastLog('倒计时：'+fenzhong+'分'+miaozhong+'秒')
// } else {
//     let miaozhong = Math.trunc(timeDifference/1000)
//     toastLog('倒计时：'+miaozhong+'秒')
// }


// setTimeout(function(){
//     // 循环点击召唤
//     for (let index = 0; index < 116; index++) {
//         click(1164, 1001);
//         sleep(60)
//         click(1200, 866);
//         sleep(20)
//     }
// },timeDifference)

// var kaishizhaohuan = images.read("./img/kaishizhaohuan2.png");
// //截图并找图
// var p = findImage(captureScreen(), kaishizhaohuan, { threshold: 0.2 });
// if(p){
//     toastLog("开始召唤按钮: " + p);
//     // log(p.x, p.y)
// }else{
//     toast("没找到按钮");
// }



// 看今天日期是否在表格，true 给出对应提示 false 再看是不是周一

// var MonthAndDay = getMonthAndDay(SystemTime)
// log(MonthAndDay)

// for (const key in HeroDataFrom2023) {
//     if (Object.hasOwnProperty.call(HeroDataFrom2023, key)) {
//         const element = HeroDataFrom2023[key];
//         for (const iterator of element) {
//             if (iterator == MonthAndDay) {
//                 let name = ''
//                 if (key == 'zhurong') {
//                     name = '祝融夫人'
//                 }else if(key == 'zhouwang'){
//                     name = '纣王殷寿'
//                 }else if(key == 'aobai'){
//                     name = '鳌拜'
//                 }
//                 toastLog('特殊召唤 '+ name)
//             }
//         }
//     }
// }

// 检查应用是否是英雄杀

// 获取系统时间 设置距离多长时间定时开抢 开始倒计时